<?php
namespace app\frontend\controllers;


use app\helpers\UserHelper;
use app\models\User;
use Phalcon\Mvc\Model\Criteria;
use Phalcon\Paginator\Adapter\Model as Paginator;
use app\frontend\forms\ChangePasswordForm;

/**
 * 用户控制器
 * Class UserController
 */
class UserController extends ControllerBase
{
    public function changePasswordAction(){
        $this->tag->setTitle('修改密码');
        $user = UserHelper::getUser();
        $form = new ChangePasswordForm($user);
        $req = $this->request;
        if($req->isPost()){
            $param = $req->getPost();
            $param['userpassword'] = $user->password;
            if($form->isValid($param)){
                $user->save();
                $this->response->redirect('user/changePassword');
                return;
            }
        }
        $this->view->form = $form;
    }

    public function indexAction()
    {
        $this->tag->setTitle('用户列表');

        $numberPage = 1;
        if ($this->request->isPost()) {
            $query = Criteria::fromInput($this->di, 'User', $_POST);
            $this->persistent->parameters = $query->getParams();
        } else {
            $numberPage = $this->request->getQuery("page", "int");
        }

        $parameters = $this->persistent->parameters;
        if (!is_array($parameters)) {
            $parameters = [];
        }

        $parameters["order"] = "pid";
        $user = User::find($parameters);
        if (count($user) == 0) {
            $this->flash->notice("The search did not find any user");

            $this->dispatcher->forward([
                "controller" => "user",
                "action" => "index"
            ]);

            return;
        }

        $paginator = new Paginator([
            'data' => $user,
            'limit'=> 10,
            'page' => $numberPage
        ]);
        $this->view->page = $paginator->getPaginate();
    }
}
